//
//  QCAbountViewController+Nordic.swift
//  爱汽车
//
//  Created by xinglian on 2024/4/9.
//

import UIKit
import iOSDFULibrary
import TCCKit

extension QCAboutViewController{
    ///Nordic开始OTA
    func Nordic_OTA(){
        if BLE.status != .DFU{
            BLE.status = .DFU
            BLEData.prepareOTA.write
            search()
            return
        }
        let peripheral = BLE.connectedPeripherals.first!
        let initiator = DFUServiceInitiator.init(centralManager:BLE.central, target:peripheral)
        let selectedFirmware = DFUFirmware.init(urlToZipFile: URL(string:current_OTA_Model.localPath)!)
        _ = initiator.with(firmware: selectedFirmware!)
        initiator.delegate = self
        initiator.logger = self
        initiator.progressDelegate = self
        initiator.packetReceiptNotificationParameter = UInt16((UserDefaults.standard.value(forKey:"dfu_number_of_packets")as! NSNumber).intValue)
        initiator.enableUnsafeExperimentalButtonlessServiceInSecureDfu = true
        _ = initiator.start(target: peripheral)///支持开始暂停
    }
    
}
//MARK: - NODIC官方ota DFUProgressDelegate
//MARK: - DFUServiceDelegate,LoggerDelegate
extension QCAboutViewController : DFUProgressDelegate,DFUServiceDelegate,LoggerDelegate
{
    internal func dfuProgressDidChange(for part: Int, outOf totalParts: Int, to progress: Int, currentSpeedBytesPerSecond: Double, avgSpeedBytesPerSecond: Double) {
        let title = LS("已完成") + ":" + "\(progress)%"
        btnState(text: title, index: btn_select_index)
    }
    
    internal func dfuStateDidChange(to state: DFUState) {
        switch state {
        case .connecting, .starting, .uploading:
            btnState(text:"升级开始", index:btn_select_index)
        case .completed:
            _ = BLE.connectedPeripherals.map{
                if OTAName.contains($0.name ?? ""){
                    BLE.disConnect($0)
                }
            }
//            BLE.status = .DFU
            btnState(text:"已是最新", index:btn_select_index)
            CCHud.start(LS("重启中"), stopTime: 5){
                BLE.status = .normal
            }
        default:
            break
        }
    }
    
    internal func dfuError(_ error: DFUError, didOccurWithMessage message: String)
    {
        otaStatus = .done
        btnState(text:"升级失败", index:btn_select_index)
    }
    internal func logWith(_ level: LogLevel, message: String) {
        //print("====loglevel=\(level), message = \(message)")
    }
}
//MARK: - NODIC官方ota - END
